import { FC, ReactElement, useEffect, useRef, useState } from 'react'
import {
  connect,
  Dispatch,
  IndicatorListType,
  IndicatorModelState,
  history
} from 'umi'
import type { ColumnsType } from 'antd/es/table'
import { Table, Card, Form, Button, Input, Modal, message, Space } from 'antd'
import type { FormInstance } from 'antd'
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons'
import AddIndicator from './components/add-indicator'
import EditIndicator from './components/edit-indicator'
import styles from './index.less'
interface IProps {
  dispatch: Dispatch
  indicatorModel: IndicatorModelState
}

// 索引签名，任意属性
interface FormValues {
  [name: string]: any
}

const Indicator: FC<IProps> = ({ dispatch, indicatorModel }): ReactElement => {
  const formRef = useRef<FormInstance>(null)
  const { indicatorList } = indicatorModel
  const [addShow, setAddShow] = useState<boolean>(false)
  const [editShow, setEditShow] = useState<boolean>(false)
  const [record, setRecord] = useState<IndicatorListType | undefined>(undefined)
  const [pageNum, setPageNum] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(10)
  const [total, setTotal] = useState<number>(0)

  const paginationProps = {
    current: pageNum, //当前页码
    pageSize, // 每页数据条数
    showTotal: () => <span>总共{total}项</span>,
    total, // 总条数
    onChange: (page: number, pageSize: number) =>
      handlePageChange(page, pageSize), //改变页码的函数
    hideOnSinglePage: false,
    showSizeChanger: false
  }

  const handlePageChange = (page: number, pageSize: number) => {
    setPageNum(page)
    setPageSize(pageSize)
  }

  // 删除指标
  const deleteIndicator = (code: string): void => {
    Modal.confirm({
      title: '删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定删除该指标吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'indicatorModel/function_deleteRuleInfo',
          payload: {
            code
          },
          callback: (response) => {
            if (response.code === 200) {
              message.success('删除成功')
              formRef.current?.submit()
            }
          }
        })
      }
    })
  }

  // 查看指标详情
  const indicatorDetail = (ruleCode: string) => {
    history.replace({
      pathname: '/indicator/detail',
      query: {
        ruleCode
      }
    })
  }

  // 编辑用户
  const editUser = (record: IndicatorListType): void => {
    setRecord(record)
    setEditShow(true)
  }

  const columns: ColumnsType<IndicatorListType> = [
    {
      title: '序号',
      key: 'index',
      align: 'center',
      render: (_: string, record: IndicatorListType, index: number) => {
        return (
          <span>
            {((pageNum - 1) * pageSize + (index + 1))
              .toString()
              .padStart(2, '0')}
          </span>
        )
      }
    },
    {
      title: '指标名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center'
    },
    {
      title: '备注',
      dataIndex: 'desc',
      key: 'desc',
      align: 'center',
      render: (desc: string) => {
        return <span>{desc || '暂无'}</span>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center'
    },
    {
      title: '操作',
      render: (_: string, record: IndicatorListType) => {
        return (
          <Space size="large">
            <Button type="primary" onClick={() => editUser(record)}>
              修改
            </Button>
            <Button type="primary" onClick={() => indicatorDetail(record.code)}>
              查看详情
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => deleteIndicator(record.code)}
            >
              删除
            </Button>
          </Space>
        )
      },
      align: 'center'
    }
  ]

  const onFinish = (values: FormValues) => {
    const { name } = values
    getIndicatorList(name)
  }
  const resetForm = () => {
    formRef.current?.resetFields()
    setPageNum(1)
    setPageSize(10)
    getIndicatorList()
  }

  // 获取指标列表
  const getIndicatorList = (name?: string) => {
    dispatch({
      type: 'indicatorModel/function_getRuleInfo',
      payload: { name }
    })
  }

  // 新增或修改成功刷新用户列表
  const handleUpdate = () => {
    formRef.current?.submit()
  }

  // 添加用户
  const addIndicator = () => {
    setAddShow(true)
  }

  useEffect(() => {
    getIndicatorList()
  }, [])

  useEffect(() => {
    setTotal(indicatorList.length)
    if (Math.ceil(indicatorList.length / 10) < pageNum && pageNum > 1) {
      setPageNum((prev) => prev - 1)
    }
  }, [indicatorList])

  return (
    <div className={styles.container}>
      <Card>
        <div className={styles['form-wrapper']}>
          <Form layout={'inline'} onFinish={onFinish} ref={formRef}>
            <Form.Item label="指标名称" name="name">
              <Input placeholder="请输入指标名称" />
            </Form.Item>
            <Form.Item>
              <Space size="large">
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button onClick={resetForm}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
          <Button icon={<PlusOutlined />} onClick={addIndicator}>
            添加指标
          </Button>
        </div>

        <Table
          dataSource={indicatorList}
          columns={columns}
          rowKey="code"
          pagination={paginationProps}
        />
      </Card>

      {/* 添加指标 */}
      <AddIndicator
        visible={addShow}
        hide={() => {
          setAddShow(false)
        }}
        update={handleUpdate}
      />

      {/* 编辑指标 */}
      <EditIndicator
        visible={editShow}
        hide={() => {
          setEditShow(false)
        }}
        record={record}
        update={handleUpdate}
      />
    </div>
  )
}

const mapStateToProps = ({
  indicatorModel
}: {
  indicatorModel: IndicatorModelState
}) => {
  return {
    indicatorModel
  }
}
export default connect(mapStateToProps)(Indicator)
